<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-select-warehouse-modal
                v-model="queryParam.warehouseId"
                placeholder="请选择仓库"
                @change="onWarehouseChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="库位编号">
              <a-input placeholder="请输入库位编号" v-model="queryParam.locationCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="库位名称">
              <a-input placeholder="请输入库位名称" v-model="queryParam.locationName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="wms_location_status" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus" v-if="hasPermission('wms:location:add')">新增</a-button> -->
      <a-button @click="handleBatchGenerate" type="primary" icon="plus-circle" v-if="hasPermission('wms:location:add')"
        >批量生成</a-button
      >
      <a-button @click="handleBatchPrint" type="primary" icon="printer" v-if="hasPermission('wms:location:view')"
        >批量打印二维码</a-button
      >
      <a-button
        type="primary"
        icon="download"
        @click="handleExportXls('库位信息')"
        v-if="hasPermission('wms:location:export')"
        >导出</a-button
      >
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:location:delete')">
            <a-icon type="delete" />删除
          </a-menu-item>
          <a-menu-item key="2" @click="batchPrintQrcode" v-if="hasPermission('wms:location:view')">
            <a-icon type="printer" />打印所选二维码
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="hasPermission('wms:location:edit')">编辑</a>
          <a-divider
            type="vertical"
            v-if="
              hasPermission('wms:location:edit') && (record.warehouseType === '5' || hasPermission('wms:location:view'))
            "
          />
          <a
            @click="handleBindMaterial(record)"
            v-if="record.warehouseType === '5' && hasPermission('wms:location:edit')"
            >绑定物料</a
          >
          <a-divider
            type="vertical"
            v-if="
              record.warehouseType === '5' && hasPermission('wms:location:edit') && hasPermission('wms:location:view')
            "
          />
          <a @click="handlePrintSingleQrcode(record)" v-if="hasPermission('wms:location:view')">打印二维码</a>
          <a-divider
            type="vertical"
            v-if="
              (hasPermission('wms:location:edit') || hasPermission('wms:location:view')) &&
              hasPermission('wms:location:delete')
            "
          />
          <a-popconfirm
            title="确定删除吗?"
            @confirm="() => handleDelete(record.id)"
            v-if="hasPermission('wms:location:delete')"
          >
            <a>删除</a>
          </a-popconfirm>
        </span>

        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="getStatusColor(text)">
            <j-dict-label :value="text" dictCode="wms_location_status" />
          </a-tag>
        </template>

        <template slot="materialCodeListSlot" slot-scope="text, record">
          <div v-if="text && text.trim()">
            <a-tooltip placement="top" :title="text">
              <span style="cursor: pointer; color: #1890ff">
                {{ text.length > 20 ? text.substring(0, 20) + '...' : text }}
              </span>
            </a-tooltip>
          </div>
          <span v-else style="color: #999">未绑定</span>
        </template>

        <template slot="qrcodeSlot" slot-scope="text, record">
          <div v-if="text">
            <a-popover placement="right" trigger="hover">
              <template slot="content">
                <div style="text-align: center">
                  <img :src="getImgView(text)" style="max-width: 200px; max-height: 200px" />
                  <div style="margin-top: 8px">
                    <a-button type="primary" size="small" @click="handlePrintQRCode(record)">
                      <a-icon type="printer" />打印二维码
                    </a-button>
                    <a-button size="small" style="margin-left: 8px" @click="handleViewQRCode(text)">
                      <a-icon type="eye" />查看大图
                    </a-button>
                  </div>
                </div>
              </template>
              <img
                :src="getImgView(text)"
                style="max-width: 50px; max-height: 50px; cursor: pointer"
                @click="handleViewQRCode(text)"
              />
            </a-popover>
          </div>
          <span v-else>暂无二维码</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <warehouse-location-modal ref="modalForm" @ok="modalFormOk"></warehouse-location-modal>
    <warehouse-location-batch-modal ref="batchModalForm" @ok="modalFormOk"></warehouse-location-batch-modal>

    <!-- 绑定物料模态框 -->
    <a-modal
      title="绑定物料"
      :visible="bindMaterialVisible"
      @ok="handleBindMaterialOk"
      @cancel="handleBindMaterialCancel"
      :confirmLoading="bindMaterialLoading"
      width="600px"
    >
      <a-form :form="bindMaterialForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="库位信息">
          <span>{{ currentLocation.locationName }} ({{ currentLocation.locationCode }})</span>
        </a-form-item>
        <a-form-item label="物料编号" help="请输入物料编号，多个用逗号分隔，且必须逗号结尾，例如：M001,M002,M003,">
          <a-textarea
            v-decorator="[
              'materialCodeList',
              {
                rules: [{ required: true, message: '请输入物料编号' }],
              },
            ]"
            placeholder="请输入物料编号，多个用逗号分隔，且必须逗号结尾，例如：M001,M002,M003,"
            :rows="4"
            :maxLength="500"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import WarehouseLocationModal from './modules/WarehouseLocationModal'
import WarehouseLocationBatchModal from './modules/WarehouseLocationBatchModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import JDictLabel from '@/components/dict/JDictLabel.vue'
import {
  warehouseLocationList,
  warehouseLocationDelete,
  warehouseLocationDeleteBatch,
  warehouseLocationExport,
  warehouseLocationEdit,
} from '@/api/wms'
import { getFileAccessHttpUrl, downFile } from '@/api/manage'
import JSelectWarehouseModal from '@/components/jeecgbiz/JSelectWarehouseModal.vue'

export default {
  name: 'WarehouseLocationList',
  mixins: [JeecgListMixin],
  components: {
    WarehouseLocationModal,
    WarehouseLocationBatchModal,
    JDictSelectTag,
    JDictLabel,
    JSelectWarehouseModal,
  },
  data() {
    return {
      description: '库位管理',
      warehouseId: '',
      // 查询条件
      queryParam: {},
      // 权限数据
      permissionList: [],
      // 排序参数
      isorter: {
        column: 'locationCode',
        order: 'asc',
      },
      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '库位编号',
          align: 'center',
          dataIndex: 'locationCode',
        },
        {
          title: '库位名称',
          align: 'center',
          dataIndex: 'locationName',
        },
        {
          title: '所属仓库',
          align: 'center',
          dataIndex: 'warehouseName',
          customRender: (text) => {
            return text || '未知仓库'
          },
        },
        {
          title: '库位二维码',
          align: 'center',
          dataIndex: 'locationQrcode',
          scopedSlots: { customRender: 'qrcodeSlot' },
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '绑定物料',
          align: 'center',
          dataIndex: 'materialCodeList',
          width: 150,
          scopedSlots: { customRender: 'materialCodeListSlot' },
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: warehouseLocationList,
        delete: warehouseLocationDelete,
        deleteBatch: warehouseLocationDeleteBatch,
        exportXlsUrl: warehouseLocationExport,
      },
      // 状态颜色映射
      statusColors: {
        0: 'green', // 启用
        1: 'red', // 禁用
        2: 'orange', // 已占用
        3: 'purple', // 已满
      },
      // 绑定物料相关
      bindMaterialVisible: false,
      bindMaterialLoading: false,
      bindMaterialForm: this.$form.createForm(this),
      currentLocation: {},
    }
  },
  created() {
    if (this.$route.query.warehouseId) {
      this.warehouseId = this.$route.query.warehouseId
      this.queryParam.warehouseId = this.warehouseId
    }
    // 加载权限数据
    this.loadPermissionData()

    // 加载字典数据
    this.initDictConfig()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    // 获取图片访问路径
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },

    // 打印二维码
    handlePrintQRCode(record) {
      const imgUrl = this.getImgView(record.locationQrcode)
      const locationName = record.locationName || record.locationCode

      // 创建打印窗口
      const printWindow = window.open('', '_blank')
      printWindow.document.write(`
          <html>
            <head>
              <title>打印库位二维码 - ${locationName}</title>
              <style>
                body {
                  font-family: Arial, sans-serif;
                  text-align: center;
                  padding: 20px;
                }
                .qrcode-container {
                  margin: 0 auto;
                  width: 300px;
                }
                .qrcode-title {
                  font-size: 18px;
                  font-weight: bold;
                  margin-bottom: 10px;
                }
                .qrcode-code {
                  font-size: 14px;
                  margin-bottom: 10px;
                }
                .qrcode-image {
                  width: 100%;
                  max-width: 300px;
                  height: auto;
                }
                @media print {
                  button {
                    display: none;
                  }
                }
              </style>
            </head>
            <body>
              <div class="qrcode-container">
                <div class="qrcode-title">${locationName}</div>
                <div class="qrcode-code">编码: ${record.locationCode}</div>
                <img src="${imgUrl}" class="qrcode-image" />
              </div>
              <button style="margin-top: 20px;" onclick="window.print()">打印</button>
            </body>
          </html>
        `)
      printWindow.document.close()
    },

    // 查看二维码大图
    handleViewQRCode(qrcodeUrl) {
      const imgUrl = this.getImgView(qrcodeUrl)

      // 使用a-modal组件显示大图
      this.$confirm({
        title: '查看二维码',
        width: 400,
        content: (h) => {
          return h(
            'div',
            {
              style: {
                textAlign: 'center',
              },
            },
            [
              h('img', {
                attrs: {
                  src: imgUrl,
                },
                style: {
                  maxWidth: '100%',
                  maxHeight: '350px',
                },
              }),
            ]
          )
        },
        okText: '关闭',
      })
    },

    // 获取状态对应的颜色
    getStatusColor(status) {
      return this.statusColors[status] || 'blue'
    },

    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }

      // 构建查询参数
      const params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        ...this.queryParam,
      }

      // 添加排序参数
      if (this.isorter.column) {
        params.column = this.isorter.column
        params.order = this.isorter.order
      }

      console.log('执行查询，参数:', params)
      this.loading = true
      warehouseLocationList(params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total || 0
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    searchReset() {
      // 完全重置所有查询条件
      this.queryParam = {}
      this.warehouseId = ''

      // 由于j-select-warehouse-modal组件绑定的是queryParam.warehouseId
      // 需要确保组件显示也被重置
      this.$nextTick(() => {
        // 强制更新视图以确保组件重置
        this.$forceUpdate()
      })

      this.loadData(1)
    },

    searchQuery() {
      console.log('执行查询，参数:', this.queryParam)
      this.loadData(1)
    },

    // 重写getQueryField方法，确保返回正确的字段列表
    getQueryField() {
      // 返回需要的字段，不包含多余的逗号
      return 'id,locationCode,locationName,locationQrcode,status,remark,warehouseId'
    },

    handleDelete(id) {
      warehouseLocationDelete({ id: id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    batchDel() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择至少一条记录')
        return
      }
      let ids = this.selectedRowKeys.join(',')
      let that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function () {
          that.loading = true
          warehouseLocationDeleteBatch({ ids: ids })
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
      })
    },

    // 加载权限数据
    loadPermissionData() {
      // 获取用户权限列表
      const userAuth = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]')
      const sysAuth = JSON.parse(sessionStorage.getItem('SYS_BUTTON_AUTH') || '[]')

      // 合并权限数据
      this.permissionList = []

      // 处理用户权限
      userAuth.forEach((auth) => {
        if (typeof auth === 'string') {
          this.permissionList.push(auth)
        } else if (auth && auth.action) {
          this.permissionList.push(auth.action)
        }
      })

      // 处理系统权限
      sysAuth.forEach((auth) => {
        if (typeof auth === 'string') {
          if (!this.permissionList.includes(auth)) {
            this.permissionList.push(auth)
          }
        } else if (auth && auth.action) {
          if (!this.permissionList.includes(auth.action)) {
            this.permissionList.push(auth.action)
          }
        }
      })
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 处理表格变化（排序、分页等）
    handleTableChange(pagination, filters, sorter) {
      // 处理排序
      if (sorter && sorter.field) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc'
      }

      // 处理分页
      this.ipagination = pagination

      // 重新加载数据
      this.loadData()
    },

    handleAdd() {
      this.$refs.modalForm.add(this.warehouseId)
      this.$refs.modalForm.title = '新增库位'
    },

    handleBatchGenerate() {
      this.$refs.batchModalForm.show(this.warehouseId)
      this.$refs.batchModalForm.title = '批量生成库位'
    },

    // 处理单个库位二维码打印
    handlePrintSingleQrcode(record) {
      if (!record || !record.locationQrcode) {
        this.$message.warning('该库位没有二维码，无法打印')
        return
      }
      this.handlePrintQRCode(record)
    },

    // 批量打印所选库位的二维码
    batchPrintQrcode() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请至少选择一个库位')
        return
      }

      // 获取所选行的数据
      const selectedRecords = this.dataSource.filter((item) => this.selectedRowKeys.includes(item.id))

      // 创建打印窗口
      const printWindow = window.open('', '_blank')

      // 生成打印页面HTML
      let htmlContent = `
          <html>
            <head>
              <title>批量打印库位二维码</title>
              <style>
                body {
                  font-family: Arial, sans-serif;
                  margin: 0;
                  padding: 20px;
                }
                .qrcode-grid {
                  display: flex;
                  flex-wrap: wrap;
                  justify-content: space-around;
                }
                .qrcode-item {
                  width: 300px;
                  margin: 10px;
                  padding: 10px;
                  border: 1px solid #ddd;
                  text-align: center;
                  page-break-inside: avoid;
                }
                .qrcode-title {
                  font-size: 16px;
                  font-weight: bold;
                  margin-bottom: 8px;
                }
                .qrcode-code {
                  font-size: 12px;
                  margin-bottom: 8px;
                }
                .qrcode-image {
                  width: 100%;
                  max-width: 250px;
                  height: auto;
                }
                @media print {
                  button {
                    display: none;
                  }
                  .no-print {
                    display: none;
                  }
                  .qrcode-item {
                    break-inside: avoid;
                  }
                }
              </style>
            </head>
            <body>
              <div class="no-print" style="text-align:center; margin-bottom: 20px;">
                <h2>批量打印库位二维码</h2>
                <button onclick="window.print()">打印</button>
              </div>
              <div class="qrcode-grid">
        `

      // 添加每个库位的二维码
      selectedRecords.forEach((record) => {
        if (record.locationQrcode) {
          const imgUrl = this.getImgView(record.locationQrcode)
          const locationName = record.locationName || record.locationCode

          htmlContent += `
              <div class="qrcode-item">
                <div class="qrcode-title">${locationName}</div>
                <div class="qrcode-code">编码: ${record.locationCode}</div>
                <img src="${imgUrl}" class="qrcode-image" />
              </div>
            `
        }
      })

      // 结束HTML
      htmlContent += `
              </div>
            </body>
          </html>
        `

      // 写入内容并关闭文档流
      printWindow.document.write(htmlContent)
      printWindow.document.close()
    },

    // 批量打印当前仓库下所有库位的二维码
    handleBatchPrint() {
      // 构建查询参数，保留现有查询条件
      const params = {
        ...this.queryParam,
        pageNo: 1,
        pageSize: 500, // 设置较大的页面大小以尝试获取所有库位
      }

      this.loading = true
      // 获取当前查询条件下的所有库位
      warehouseLocationList(params)
        .then((res) => {
          if (res.success) {
            const locationList = res.result.records || []

            if (locationList.length === 0) {
              this.$message.warning('没有可打印的库位二维码')
              return
            }

            // 创建打印窗口
            const printWindow = window.open('', '_blank')

            // 生成打印页面HTML
            let htmlContent = `
              <html>
                <head>
                  <title>批量打印库位二维码</title>
                  <style>
                    body {
                      font-family: Arial, sans-serif;
                      margin: 0;
                      padding: 20px;
                    }
                    .qrcode-grid {
                      display: flex;
                      flex-wrap: wrap;
                      justify-content: space-around;
                    }
                    .qrcode-item {
                      width: 300px;
                      margin: 10px;
                      padding: 10px;
                      border: 1px solid #ddd;
                      text-align: center;
                      page-break-inside: avoid;
                    }
                    .qrcode-title {
                      font-size: 16px;
                      font-weight: bold;
                      margin-bottom: 8px;
                    }
                    .qrcode-code {
                      font-size: 12px;
                      margin-bottom: 8px;
                    }
                    .qrcode-image {
                      width: 100%;
                      max-width: 250px;
                      height: auto;
                    }
                    @media print {
                      button {
                        display: none;
                      }
                      .no-print {
                        display: none;
                      }
                      .qrcode-item {
                        break-inside: avoid;
                      }
                    }
                  </style>
                </head>
                <body>
                  <div class="no-print" style="text-align:center; margin-bottom: 20px;">
                    <h2>批量打印库位二维码</h2>
                    <p>共 ${locationList.length} 个库位二维码</p>
                    <button onclick="window.print()">打印</button>
                  </div>
                  <div class="qrcode-grid">
            `

            // 添加每个库位的二维码
            locationList.forEach((record) => {
              if (record.locationQrcode) {
                const imgUrl = this.getImgView(record.locationQrcode)
                const locationName = record.locationName || record.locationCode

                htmlContent += `
                  <div class="qrcode-item">
                    <div class="qrcode-title">${locationName}</div>
                    <div class="qrcode-code">编码: ${record.locationCode}</div>
                    <img src="${imgUrl}" class="qrcode-image" />
                  </div>
                `
              }
            })

            // 结束HTML
            htmlContent += `
                  </div>
                </body>
              </html>
            `

            // 写入内容并关闭文档流
            printWindow.document.write(htmlContent)
            printWindow.document.close()
          } else {
            this.$message.warning(res.message || '获取库位数据失败')
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleEdit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑库位'
    },

    modalFormOk() {
      this.loadData()
    },

    // 仓库选择变更事件
    onWarehouseChange(value, selectedWarehouses) {
      if (value) {
        this.warehouseId = value
        this.queryParam.warehouseId = value
      } else {
        this.warehouseId = ''
        this.queryParam.warehouseId = ''
      }
      this.loadData(1)
    },

    // 绑定物料
    handleBindMaterial(record) {
      this.currentLocation = record
      this.bindMaterialVisible = true
      // 设置表单初始值
      this.$nextTick(() => {
        this.bindMaterialForm.setFieldsValue({
          materialCodeList: record.materialCodeList || '',
        })
      })
    },

    // 绑定物料确认
    handleBindMaterialOk() {
      this.bindMaterialForm.validateFields((err, values) => {
        if (!err) {
          this.bindMaterialLoading = true
          const updateData = {
            ...this.currentLocation,
            materialCodeList: values.materialCodeList.trim(),
          }

          warehouseLocationEdit(updateData)
            .then((res) => {
              if (res.success) {
                this.$message.success('绑定物料成功！')
                this.bindMaterialVisible = false
                this.bindMaterialForm.resetFields()
                this.loadData() // 刷新列表
              } else {
                this.$message.error(res.message || '绑定物料失败')
              }
            })
            .catch((error) => {
              console.error('绑定物料失败:', error)
              this.$message.error('绑定物料失败，请稍后重试')
            })
            .finally(() => {
              this.bindMaterialLoading = false
            })
        }
      })
    },

    // 绑定物料取消
    handleBindMaterialCancel() {
      this.bindMaterialVisible = false
      this.bindMaterialForm.resetFields()
      this.currentLocation = {}
    },

    // 导出Excel
    handleExportXls(title) {
      if (!title || typeof title != 'string') {
        title = '库位信息'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      this.loading = true
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), title + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', title + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
        this.loading = false
      })
    },
  },
}
</script>

<style scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}
.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}
.anty-row-operator button {
  margin: 0 5px;
}
.ant-btn-danger {
  background-color: #ffffff;
}
.ant-modal-cust-warp {
  height: 100%;
}
.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}
.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

/* 仓库下拉框样式 */
.warehouse-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.warehouse-name {
  font-weight: 500;
}
.warehouse-code {
  color: #999;
  font-size: 12px;
}
</style> 